package xyz.xiangyushui.util.codeLineCounter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;

public class CodeLineCounter {
	private File file;
	private int lineCount;
	
	public CodeLineCounter(File file){
		lineCount=0;
		this.file=file;
	}
	
	public void start(){
		if(file.isDirectory()){
			System.out.println(countADirectory(file,f->f.getName().endsWith(".java")||f.getName().endsWith(".jsp")));
		}else if(file.isFile()){
			System.out.println(countAFile(file));
		}
	}
	
	public int countAFile(File file){
		int lineCount = 0;
		BufferedReader br = null;
		try {
			br=new BufferedReader(new FileReader(file));
			while(br.readLine()!=null){
				lineCount++;
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}finally{
			if(br!=null){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return lineCount;
	}
	
	public int countADirectory(File directory,FileFilter filter){
		File[] files=directory.listFiles();
		for(File file:files){
			if(filter.accept(file)){
				int add=countAFile(file);
				System.out.println(file.getAbsolutePath()+"  "+add+" lines");
				lineCount+=add;
			}else if(file.isDirectory()){
				countADirectory(file,filter);
			}
		}
		return lineCount;
	}
	
	
	public static void main(String[] args){
		CodeLineCounter clc=new CodeLineCounter(new File(System.getProperty("user.dir")));
		clc.start();
	}
	
}
